var map = null; //地图对象
var startPoint=null;
var endPoint=null;
var polygon=null;

var driving=null;
var points=[];
var pointObj=[];
var ctx = window.daijia.ctx;
var mapLoadFinish = false;
var index = 0;
var myGeo=null;
var polyline=null;
var tempmarkers=[];
var flag=true;
function initialize(center){
   myGeo = new BMap.Geocoder();
	myGeo.getPoint(center, function(point){
		if (point) {
			map = new BMap.Map("allmap");
			map.centerAndZoom(point, 13);
		    map.enableScrollWheelZoom();
		    ///三种驾车策略：最少时间，最短距离，避开高速    BMAP_DRIVING_POLICY_LEAST_TIME,BMAP_DRIVING_POLICY_LEAST_DISTANCE,BMAP_DRIVING_POLICY_AVOID_HIGHWAYS
		    driving = new BMap.DrivingRoute(map, {policy : BMAP_DRIVING_POLICY_LEAST_DISTANCE});
		    driving.setSearchCompleteCallback(function(){
		        var pts = driving.getResults().getPlan(0).getRoute(0).getPath();    //通过驾车实例，获得一系列点的数组
		        polyline = new BMap.Polyline(pts);     
		        map.addOverlay(polyline);
		        if(flag){
		        	bdGEO();
		        	flag=false;
		        }
		       setTimeout(function(){
		            map.setViewport(points);          //调整到最佳视野
		        },200);
		    });
		 
		    //右键菜单
		    var contextMenu = new BMap.ContextMenu();
			var txtMenuItem = [{
			   text:'设为行驶地',
			   callback:function(p){
				   index=0;
				   flag=true;
				   points[points.length]=p;
				   pointObj=[];
				  
				   if(points.length==1){
					    var marker = new BMap.Marker(p); 
				        myGeo.getLocation(p, function(rs){
							   var addComp = rs.addressComponents;
							   var address=addComp.district + " "+ addComp.street;
							   var lab = new BMap.Label(address,{offset:new BMap.Size(-30,-15)});
								lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
								marker.setLabel(lab); 
								$("#wayAddress").val(address);
						    }); 
				       
						    map.addOverlay(marker);
				   }else if(points.length>1){
					   map.clearOverlays();           
					  for(var i=0;i<points.length-1;i++){
						  driving.search(points[i],points[i+1]);
					  }	
					  myGeo.getLocation(p, function(rs){
						   var addComp = rs.addressComponents;
						   var address=addComp.district + " "+ addComp.street;
					var str = 
						   "<div>"+
							   "<div class='col-sm-10' style='margin-left:-15px;'>"+
				                       "<input class='form-control address' onblur='position(this)' index='"+(++pointIndex)+"'placeholder='添加地点' type='text' value='"+address+"' autocomplete='off'></input>"+
				               "</div>"+
				               "<div>"+
						          "<button  type='button'class='sub btn btn-default btn-sm' title='删除'>"+
				                  "<span class='glyphicon glyphicon-minus'></span>"+ 
				                  "</button>"+ 
			                 "</div>"+
				            "</div>"+   
			              "<p/> ";
			             $("#list").append(str);
					    });
				   }
				   
			   }
			},{
			   text:'清除',
			   callback:function(p){
				   
				   map.clearOverlays();
				   points=[];
				   start=[];
				   end=[];
				   ways=[];
				   startPoint=null;
				   endPoint=null;
			   }
			}];
			
			for(var i=0; i < txtMenuItem.length; i++){
				contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
				if(i==1 || i==3) {
					contextMenu.addSeparator();
				}
			}
			map.addContextMenu(contextMenu); 
			

		    //地图加载完毕
		   
		}
		else{
			$.scojs_message("地区"+center+"位置不准确，请重新编辑地区", $.scojs_message.TYPE_ERROR);
		}
	});
	
	
	
};

function bdGEO(){	
	var pt = points[index];
	geocodeSearch(pt);
	
	index++;
}
function geocodeSearch(pt){
	if(index < points.length-1){
		setTimeout(window.bdGEO,100);
	} 
	myGeo.getLocation(pt, function(rs){
		var addComp = rs.addressComponents;
		var m = new BMap.Marker(pt);
		tempmarkers[tempmarkers.length]=m;
		var  str= addComp.district + " " + addComp.street;
		var lab = new BMap.Label(str,{offset:new BMap.Size(-30,-15)});
		lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
		m.setLabel(lab);
		map.addOverlay(m);
		var obj = new Object();
		obj.address=str;
		obj.lng=pt.lng;
		obj.lat=pt.lat;
		obj.sequence=pointObj.length;
		pointObj[pointObj.length]=obj;
	});
	 
}

function position(address){
	var tempIndex=parseInt($(address).attr("index"));
	if($(address).val()==''){
		$.scojs_message("请填写地点", $.scojs_message.TYPE_ERROR);
	}else{
		map.clearOverlays();
		var local = new BMap.LocalSearch(map, {
			renderOptions:{map: map, autoViewport:true}
		});
		
		var length = points.length;
		local.search($(address).val());
		local.setInfoHtmlSetCallback(function(poi,marker,html){
	    	   index=0;
	    	   flag=true;
	    	   if(points[tempIndex]!=undefined){
	    		   points.splice(tempIndex,1,poi.point);
	    	   }else{
	    		   points[length]=poi.point;
	    	   }
			 //  points[length]=poi.point;
			   pointObj=[];
			   
	    	   if(points.length==1){
					 var markers = map.getOverlays();
					for(var i=0;i<markers.length;i++){
						markers[i].show();
					}
			   }else if(points.length>1){
				   var markers = map.getOverlays();
					for(var i=0;i<markers.length;i++){
						markers[i].show();
					}
					for(var i=0;i<tempmarkers.length;i++){
						tempmarkers[i].hide();
					}
					poi.marker.hide(); 
					map.removeOverlay(polyline);
					
					
				  for(var i=0;i<points.length-1;i++){
					  driving.search(points[i],points[i+1]);
				  }	 
			   }
	    	   
	    });
	}

}


var pointIndex=0;
$(function(){
	initialize(window.daijia.center);
	$("#city").val(window.daijia.center);
	$("#city").change(function(){
		map.centerAndZoom($(this).val(), 11);
	});
	$("#add").click(function(){
		var str ="<div>"+
				     "<div class='col-sm-10' style='margin-left:-15px;'>"+
		                  "<input class='form-control address' onblur='position(this)' index='"+(++pointIndex)+"'placeholder='添加地点' type='text' value='' autocomplete='off'></input>"+
			         "</div>"+
			         "<div>"+
				          "<button  type='button'class='sub btn btn-default btn-sm' title='删除'>"+
		                  "<span class='glyphicon glyphicon-minus'></span>"+ 
		                  "</button>"+ 
	                 "</div>"+
                 "</div>"+
                 "<p/>";
		$("#list").append(str);
		
	});
	 $(document).on("click",".sub",function(){
		 var temp =  parseInt($(this).parent().prev('div').children('input').attr("index"));
		 if(points[temp]!=undefined){
			  points.splice(temp,1);
			  $(this).parent().parent().remove();
			  var inputs =$(".address");
			  for(var i=0;i<inputs.length;i++){
				  $(inputs.get(i)).attr("index",i);
			  }
			  map.clearOverlays();
			  if(inputs.length==1){
				 
				  var marker = new BMap.Marker(points[0]); 
			        myGeo.getLocation(points[0], function(rs){
						   var addComp = rs.addressComponents;
						   var address=addComp.district + " "+ addComp.street;
						   var lab = new BMap.Label(address,{offset:new BMap.Size(-30,-15)});
							lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
							marker.setLabel(lab); 
					    }); 
			       
					    map.addOverlay(marker);
			  }else{
				  flag=true;
				  index=0;
				  pointObj=[];
				  for(var i=0;i<points.length-1;i++){
					  driving.search(points[i],points[i+1]);
				  }	   
			  }
			 
		 }else{
			 $(this).parent().parent().remove();
		 }
		 
		 
	 });
  
	$("#submit").click(function(){
		if($("#city").val()==''){
			$.scojs_message("请填写城市名", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#name").val()==''){
			$.scojs_message("请填写线路名称", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#companyId").val()==""){
			$.scojs_message("请选择公司", $.scojs_message.TYPE_ERROR);
			return;
		}
		var temp="";
		for(var i=0;i<pointObj.length;i++){
			if(i==(pointObj.length-1)){
				var address =  pointObj[i].address;
				var lng = pointObj[i].lng;
				var lat = pointObj[i].lat;
				var sequence = pointObj[i].sequence;
				 temp=temp+'{"address":"'+address+'",';
				 temp=temp+'"sequence":'+sequence+',';
				 temp=temp+'"longitude":'+lng+',';
				 temp=temp+'"latitude":'+lat+'}';
			}else{
				var address =  pointObj[i].address;
				var lng = pointObj[i].lng;
				var lat = pointObj[i].lat;
				var sequence = pointObj[i].sequence;
				 temp=temp+'{"address":"'+address+'",';
				 temp=temp+'"sequence":'+sequence+',';
				 temp=temp+'"longitude":'+lng+',';
				 temp=temp+'"latitude":'+lat+'},';
			}
			
		}
		if(temp==""){
			$.scojs_message("请设置具体路线", $.scojs_message.TYPE_ERROR);
			return;
		}
		
		var waypoints = "["+temp+"]";
		$.post(ctx+"/workcararea/create",{
			"city":$("#city").val(),
			"name":$("#name").val(),
			"waypoint":waypoints,
			"companyId":$("#companyId").val(),
       	    "companyName":$('#companyId').find("option:selected").text(),},function(data){
			if(data.success){
				$.scojs_message("添加成功", $.scojs_message.TYPE_OK);
				setTimeout("$('#rollback').click()",500);
			}else{
				$.scojs_message("添加失败", $.scojs_message.TYPE_ERROR);
			}
			
		},"json");
		
		
	});
	
});
